# -*- coding: utf-8 -*-

"""
Created on Fri Jun  8 18:43:24 2018

@author: Administrator
"""
#%%

def cbf_clear_background(cbf_dirpath):
    
    import os
    import glob
    import subprocess
    star = r'*'
    temp = '_temp'
    clear_backgrd = '_clear_backgrd'
    cbf_filepath = glob.glob(cbf_dirpath+os.sep+star)
    print('cbf_filepath:',cbf_filepath)
    cmd_link = ' && '
    space = ' '
    condition = 'error'
    for item in cbf_filepath:
        print('item:',item)
        front_part = os.path.splitext(item)[0]
        end_part = os.path.splitext(item)[1]
        medi_filepath = front_part + temp + end_part
        output_filepath = front_part +  clear_backgrd + end_part
        #cmd_1的内容 3dcalc  -a subj_003_CBF.nii  -expr 'notzero(a+256)' -prefix subj_003_CBF_notzero.nii
        cmd_1 = r' 3dcalc  -a   ' + item + r' -expr ' + '\'' + r'notzero(a+256)' + '\'' + ' -prefix ' +  medi_filepath
        
        #cmd_2的内容 3dcalc  -a subj_003_CBF.nii -b subj_003_CBF_notzero.nii  -expr 'a*b' -prefix subj_003_CBF_masked.nii
        cmd_2 = r' 3dcalc  -a   ' + item + ' -b ' + medi_filepath  + ' -expr '  + '\'' + r'a*b' + '\'' + ' -prefix ' +  output_filepath
        
        shell_script = cmd_1 + cmd_link + cmd_2
        print(' shell_script: ',shell_script)
        popen_subj = subprocess.Popen(shell_script,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        stdout_err = popen_subj.communicate()
        if condition in stdout_err[1].decode().lower():
            print('stdout_err:',stdout_err) 

#%%